package net.guruqu.rvoView;

import java.util.Vector;

import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.Spatial.LightCombineMode;
import com.jme.scene.Spatial.TextureCombineMode;
import com.jme.scene.state.BlendState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;

public class RoadMapGroup {
	Vector<RoadMapUnit> roadMapUnits;
	Node renderNode;


	public void clear() {
		roadMapUnits.clear();
		if (renderNode != null)
			renderNode.detachAllChildren();
	}

	public RoadMapGroup() {
		roadMapUnits = new Vector<RoadMapUnit>();
	}

	public Vector<RoadMapUnit> getRoadMapUnits() {
		return roadMapUnits;
	}

	public Node getRenderNode() {
		if (renderNode == null) {
			renderNode = new Node("Road Map Group");

			renderNode.setTextureCombineMode(TextureCombineMode.Off);
			renderNode.setLightCombineMode(LightCombineMode.Off);

			ZBufferState rs = DisplaySystem.getDisplaySystem().getRenderer()
					.createZBufferState();
			rs.setFunction(ZBufferState.TestFunction.Always);
			rs.setWritable(false);
			renderNode.setRenderState(rs);

			BlendState bs = DisplaySystem.getDisplaySystem().getRenderer()
					.createBlendState();
			bs.setEnabled(true);
			bs.setBlendEnabled(true);
			renderNode.setRenderState(bs);

			LightState lightState = DisplaySystem.getDisplaySystem()
					.getRenderer().createLightState();
			lightState.setEnabled(true);
			renderNode.setRenderState(lightState);

			// TextureState state =
			// DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
			// state.setEnabled(false);
			// state.clearTextures();
			// renderNode.setRenderState(state);
			renderNode.setRenderQueueMode(Renderer.QUEUE_SKIP);
			renderNode.updateRenderState();
		}
		return renderNode;
	}

	public RoadMapUnit createNewUnit() {
		RoadMapUnit mapUnit = new RoadMapUnit();
		roadMapUnits.add(mapUnit);
		renderNode.attachChild(mapUnit.getRenderNode());
		renderNode.updateModelBound();
		return mapUnit;
	}

	public void removeUnit(RoadMapUnit rm) {
		renderNode.detachChild(rm.getRenderNode());
		roadMapUnits.remove(rm);
		renderNode.updateModelBound();
	}

	public RoadMapUnit selectUnit(float x, float y, float scale) {
		for (RoadMapUnit rm : roadMapUnits) {
			if (rm.pick(x, y, scale) != -1)
				return rm;
		}
		return null;
	}
}
